const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const { v4: uuidV4 } = require('uuid');

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

app.set('view engine', 'ejs');
app.use(express.static('public'));

app.get('/', (req, res) => {
    res.redirect(`/${uuidV4()}`);
});

app.get('/play', (req, res) => {
    res.render('play', {});
});

app.get('/:room', (req, res) => {
    res.render('room', { roomId: req.params.room });
});


io.on('connection', (socket) => {
    console.log('A user connected');

    socket.on('disconnect', () => {
        console.log('A user disconnected');
    });

    socket.on('offer', (offer) => {
        console.log('Received offer:', offer);
        // 将offer广播给其他客户端
        socket.broadcast.emit('offer', offer);
    });

    socket.on('answer', (answer) => {
        console.log('Received answer:', answer);
        // 将answer广播给其他客户端
        socket.broadcast.emit('answer', answer);
    });

    socket.on('ice-candidate', (candidate) => {
        console.log('Received ice-candidate:', candidate);
        // 将ice-candidate广播给其他客户端
        socket.broadcast.emit('ice-candidate', candidate);
    });
});

server.listen(3000, () => {
    console.log('Server is running on port 3000');
});
